﻿using System.Collections;
using UnityEngine;

public class GuideDialogCtrl : CSIMediator
{
    public int dialogId = 0;
    public bool isGuide = false;

    private int nextId = 0;
    private int musicId = 0;

    private GuideDialogPanel view;
    private TypewriterEffect writer;

    public override void SetData(params object[] args)
    {
        dialogId = (int)args[0];
        isGuide = (bool)args[1];
    }

    public override void Awake()
    {
        base.Awake(); view = new GuideDialogPanel(Go);
        writer = view.Dialog_txt.GetComponent<TypewriterEffect>();
    }

    public override void Open()
    {
        base.Open(); 
        BehaviourUtil.StartCoroutine(ReFresh(dialogId));
    }

    public override void Close()
    {
        base.Close();
    }

    public override void Destroy()
    {
        writer = null;
        view = null;
        base.Destroy();
    }

    public override void AddListener()
    {
        UIEventListener.Get(view.FullMask_sp.gameObject).onClick = OnFullClick;
    }

    public override int PanelId
    {
        get { return (int)PanelID.GuideDialogPanel; }
    }

    private IEnumerator ReFresh(int id)
    {
        if (musicId > 0) { ZMgr.SoundMgr.StopSound(musicId); }
        var table_StoryGuide = TableDataMgr.StoryGuideMgr.GetItemById(id);
        if (table_StoryGuide == null) { yield break; }

        nextId = table_StoryGuide.NextStoryId;
        musicId = table_StoryGuide.SoundId;
        string atlasPath = table_StoryGuide.StoryRes;
        string fileName = table_StoryGuide.StoryImgName;
        
        if (musicId > 0) { ZMgr.SoundMgr.PlaySound(musicId); }
        view.Dialog_txt.text = DBSystemMgr.GetSingleton().GetStringByID(table_StoryGuide.StoryContentId);
        writer.ResetToBeginning();

        ZMgr.ResourceMgr.LoadAtlasSetSp(view.LeftRole_sp, atlasPath, fileName);
        view.LeftRole_sp.MakePixelPerfect();
        view.LeftName_txt.text = PlayerData.GetSingleton().roleAttr.roleName;
    }

    private void OnFullClick(GameObject go)
    {
        if (writer.isActive) { writer.Finish(); }
        else
        {
            if (nextId > 0) //播放下一剧情
            {
                BehaviourUtil.StartCoroutine(ReFresh(nextId));
            }
            else
            {
                ZMgr.FaceCenter.CloseGuideDialog();
                if (isGuide) { ZMgr.GuideMgr.Finish(); }
                isGuide = false;
            }
        }
    }
}